package com.example.hibernate.g.collection_compononent;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.junit.Test;

import com.example.hibernate.utils.HibernateUtils;

public class TestApp_Item {
	
	@Test
	public void testSave(){
		
		Item item = new Item();
		item.setName("pic3");
		
		Image image1 = new Image();
		image1.setFilename("1.jpg");	image1.setSizeX(5);	image1.setSizeY(5);
		
		Image image2 = new Image();
		image2.setFilename("2.bmp");	image2.setSizeX(7);	image2.setSizeY(7);
		
		Image image3 = new Image();
		image3.setFilename("3.gif");	image3.setSizeX(9);	image3.setSizeY(9);
		
		item.getImageSet().add(image1);
		item.getImageSet().add(image2);
		item.getImageSet().add(image3);
		
		item.getImageBag().add(image1);
		item.getImageBag().add(image2);
		item.getImageBag().add(image3);
		
		
		Session session = HibernateUtils.openSession();
		session.beginTransaction();
		
		session.save(item);
		
		session.getTransaction().commit();
	}
	
	
	@Test
	public void testGet() {
		Session session = HibernateUtils.openSession();
		session.beginTransaction();
		
		Item item = (Item) session.get(Item.class, 5L);
		System.out.println(item);
		Hibernate.initialize(item.getImageBag());
		Hibernate.initialize(item.getImageSet());
		
		session.getTransaction().commit();
		
		
//		Bag: class org.hibernate.collection.PersistentBag
//		Bag: class org.hibernate.collection.PersistentIdentifierBag
		System.out.println("Bag: " + item.getImageBag().getClass());
		for(Image image : item.getImageBag()){
			System.out.println("\t" + image);
		}
		
		
//		Set: class org.hibernate.collection.PersistentSet
		System.out.println("Set: " + item.getImageSet().getClass());
		for(Image image : item.getImageSet()){
			System.out.println("\t" + image);
		}
	}
	
	@Test
	public void testGet_HQL(){
		Session session = HibernateUtils.openSession();
		session.beginTransaction();
		
		String hql = "FROM Item WHERE name = :name";
		Item item = (Item) session.createQuery(hql).setString("name", "pic3").uniqueResult();
		Hibernate.initialize(item.getImageBag());
		Hibernate.initialize(item.getImageSet());
		System.out.println(item);
		
		session.getTransaction().commit();
		
		for(Image image : item.getImageBag()){
			System.out.println("\t" + image);
		}
		for(Image image : item.getImageSet()){
			System.out.println("\t" + image);
		}
		
	}
}
